freqrange  = [11.5 12.5];
freqrange  = [0 2];
conditions = [1 2]; %1=audio; 2=blank; 3=light

% load study
% ----------
eeglab
[STUDY ALLEEG]  = pop_loadstudy('filename', 'nondual27subjects.study', 'filepath', pwd);
[STUDY, ALLEEG] = std_checkset(STUDY, ALLEEG);
CURRENTSTUDY    = 1; EEG = ALLEEG; CURRENTSET = [1:length(EEG)];
STUDY.changrp   = [];
[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, {}, 'allcomps', 'on');
%[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, {}, 'allcomps', 'on', 'recompute', 'on', 'erp', 'on', 'rmbase', baseline );
%[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, {}, 'allcomps', 'on', 'recompute', 'on', 'ersp', 'on', 'erspparams', ...
%    { 'cycles', 0, 'nfreqs', 50, 'baseline', -1000, 'timesout', 100, 'freqs', [2 50], 'trialbase', 'on', 'savetrials', 'on' } );
%[STUDY ALLEEG] = std_precomp(STUDY, ALLEEG, {}, 'allcomps', 'on', 'recompute', 'on', 'spec', 'on', 'specparams', { 'timerange' [-1010 -10] 'specmode' 'fft' } );
return

% get all subjects data
% ----------------
chans = 1:ALLEEG(1).nbchan; chans(21:22) = [];
STUDY = pop_erspparams(STUDY, 'subbaseline', 'off', 'ylim',[-5 5], 'timerange',[-1000 1000], 'freqrange',freqrange, 'condstats', 'off', 'groupstats', 'off');
STUDY = std_erspplot(STUDY,ALLEEG,'channels', { ALLEEG(1).chanlocs.labels }, 'plotmode', 'none'); % load data
%'cycles', [3 0.8], 'nfreqs', 50, 'baseline', -1000, 'freqs', [1.5 50], 'timesout', 'trialbase', 'on'

% get data into a large array
% ---------------------------
alldata = { [] [] [] };
for index = 1:length(chans)
    for c = 1:length(STUDY.condition)
        alldata{c}(:,:,index) = squeeze(STUDY.changrp(chans(index)).erspdata{c});
    end;
end;
for c = 1:length(STUDY.condition)
    alldata{c} = permute(alldata{c}, [1 3 2]);
end;

% compute statistics and plot new movie
% -------------------------------------
threshold = 0.01;
titlep    = sprintf('p-val bootstrap & FDR', threshold);
[pcond] = std_stat(alldata(conditions)', 'condstats', 'on', 'statistics', 'bootstrap', 'naccu', 200, 'mcorrect', 'fdr');
clear M tmpdata;
latencies = STUDY.changrp(1).ersptimes;
for index = 1:length(latencies)
    tmppcond{1} = squeeze(pcond{1}(index,:));
    for c = 1:length(conditions)
        tmpdata{c}  = squeeze(mean(alldata{conditions(c)}(index,:,:),3));
    end;
    textstr = sprintf('ERSP 0-2Hz at %2.0f ms', latencies(index));
    std_chantopo(tmpdata', 'datatype', 'erp', 'binarypval', 'off', 'condstats', tmppcond, ...
                           'chanlocs', ALLEEG(1).chanlocs(chans), 'titles', { STUDY.condition{conditions} titlep }')
    %delete(gca)
    textsc(textstr, 'title');
    drawnow;
    M(index) = getframe(gcf);
    close;
end;
movie2avi(M, 'erpmovie_ersp0-2hz_nd.avi', 'fps', 5);
